<template>
  <div>
      <a-input-search
      placeholder="请输入小说名称"
      @search="onSearch"
      enterButton="Search"
      size="large"
    />
    <a-button @click="stop">停止搜索</a-button>
    <a-table :columns="columns" :dataSource="dataSource">
        <span slot="action" slot-scope="text, record">
        <a href="javascript:;" @click="handleAdd(record)">添加</a>
      </span>
    </a-table>
  </div>
</template>

<script>
import { searchNovel, stopSearchNovel, downloadNovel } from '@/api'
import {
  CALLBACK,
  SEARCH_NOVEL,
  STOP_SEARCH_NOVEL
} from '@/api/channel'
import { mapActions, mapMutations, mapState } from 'vuex'
export default {
  data () {
    return {
      searchKey: '',
      columns: [
        { title: '名字', dataIndex: 'name' },
        { title: '链接', dataIndex: 'bookUrl' },
        // { title: '封面链接', dataIndex: 'coverUrl' },
        { title: '种类', dataIndex: 'kind' },
        { title: '作者', dataIndex: 'author' },
        {
          title: 'Action',
          key: 'action',
          scopedSlots: { customRender: 'action' }
        } 
      ],
    }
  },
  computed: {
    ...mapState({
      dataSource: state => state.searchList
    })
  },
  mounted () {
    // this.$electron.ipcRenderer.on(SEARCH_NOVEL + CALLBACK, result => {
    //   if (result.code === 200) {
    //     const list = result.data.result
    //     this.dataSource.push(...list)
    //   }
    // })
  },
  methods: {
    ...mapMutations(['SAVE_SEARCH_LIST']),
    async onSearch (e) {
      if(this.$route.query.sourceId) {
        searchNovel({ key: e, sourceId: this.$route.query.sourceId }).then(res => {
          this.SAVE_SEARCH_LIST((res || []).map(x => ({ sourceId: this.$route.query.sourceId, ...x })))
        }).catch(e => {
          console.log(e)
          this.$message.error(e.message)
        })
      } else {
      this.$socket.sendObj({ type: SEARCH_NOVEL, payload: { searchKey: e } })
      }
    },
    stop () {
      this.$socket.sendObj({ type: STOP_SEARCH_NOVEL })
    },
    handleAdd(record) {
        downloadNovel(record).then(res => {
          this.$router.push(`/novel/${res._id}`)
        }).catch(e => {
          this.$message.error(e.message)
        })
    }
  }
}
</script>

<style>

</style>